package com.bjesc_b2c.app.appraiset.mvp.view.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.bjesc_b2c.app.appraiset.R;
import com.bjesc_b2c.app.appraiset.adapter.CheckedCarItemAdapter;
import com.bjesc_b2c.app.appraiset.base.BaseActivity;
import com.bjesc_b2c.app.appraiset.http.IApiActivityRequest;
import com.bjesc_b2c.app.appraiset.utils.AliYunUtils;
import com.bjesc_b2c.app.appraiset.utils.BitmapUtil;
import com.bjesc_b2c.app.appraiset.utils.CustomSharedPreferences;
import com.bjesc_b2c.app.appraiset.utils.GralleryFinalUtils;
import com.bjesc_b2c.app.appraiset.utils.RxGralleryFinalUtils;
import com.bjesc_b2c.app.appraiset.utils.TimeListUilts;
import com.bjesc_b2c.app.appraiset.widget.popupwindow.SelectPhotoPop;
import com.google.gson.Gson;
import com.rxretrofit_build.CarPhotoID;
import com.rxretrofit_build.model.RxBusBean;
import com.rxretrofit_build.util.MapUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import app.pinggushi.bjesc.com.baserecyclerview.adapter.MultiItemTypeAdapter;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import cn.finalteam.rxgalleryfinal.rxbus.event.ImageRadioResultEvent;
import master_bean.CheckedCarItemBean;
import master_bean.SinglePhotoUpBean;
import rxretrofit_base.model.KeyBean;
import rxretrofit_base.model.ShowType;
import rxretrofit_base.model.TokenBean;
import rxretrofit_base.net.BaseSubscriber;
import rxretrofit_base.net.RxRequest;

/**
 * Created by lenovo on 2017/3/7.
 */

public class InsuranceBarDetailActivity extends BaseActivity implements MultiItemTypeAdapter.OnItemClickListener, CompoundButton.OnCheckedChangeListener, RadioGroup.OnCheckedChangeListener {

    @InjectView(R.id.tv_title)
    TextView tvTitle;
    @InjectView(R.id.tv_lack)
    TextView lackTv;
    @InjectView(R.id.tv_replace)
    TextView replaceTv;
    @InjectView(R.id.rg_scratched)
    RadioGroup scratchedRg;
    @InjectView(R.id.rg_painting)
    RadioGroup paintingRg;
    @InjectView(R.id.rg_sunken)
    RadioGroup sunkenRg;
    @InjectView(R.id.rg_corrosion)
    RadioGroup corrosionRg;
    @InjectView(R.id.cb_score_one)
    CheckBox scoreOneCb;
    @InjectView(R.id.cb_score_two)
    CheckBox scoreTwoCb;
    @InjectView(R.id.recycler_itemdetail_photo)
    RecyclerView photoRecycler;

    private List<String> fileList;   //阿里文件名
    private String sourceID;
    private String qStatus = "";
    private String rStatus = "";
    private String nStatus = "";
    private String xStatus = "";
    private String scratched = "";
    private String painting = "";
    private String sunken = "";
    private String corrosion = "";
    private boolean isSave;


    private CheckedCarItemAdapter itemAdapter;
    private List<CheckedCarItemBean> photoBeanList;
    private SelectPhotoPop photoPop;
    private int currentIndex;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_insurance_bar);
        ButterKnife.inject(this);
        initTitle();
        getData();
    }

    private void getData() {
        HashMap<String, Object> build = new MapUtil()
                .put("id",  CustomSharedPreferences.getString(this, KeyBean.CARID.valueOf(),KeyBean.FILE_NAME.valueOf()))
                .put("class_id", CarPhotoID.surfaceID)
                .put("attr_id", sourceID)
                .build();
        RxRequest.request(ShowType.SHOW, RxRequest.getClient(this, build).create(IApiActivityRequest.class).getSinglePhoto()
                , new BaseSubscriber<TokenBean<SinglePhotoUpBean>>(this) {
                    @Override
                    public void onSuccess(TokenBean<SinglePhotoUpBean> o) {
                        if (o.getStatus_code() == 9) {
                            isSave = false;
                        } else if (o.getStatus_code() == 0) {
                            isSave = true;
                        }
                        getItemList(o.getData());
                    }

                    @Override
                    public void onFailure(Throwable e) {

                    }
                });
    }

    private void initTitle() {
        sourceID = getIntent().getStringExtra("sourceID");
        if (!TextUtils.isEmpty(getIntent().getStringExtra("title"))) {
            tvTitle.setText(getIntent().getStringExtra("title"));
        }
    }

    private void getItemList(SinglePhotoUpBean data) {
        photoBeanList = new ArrayList<>();
        fileList = new ArrayList<>();
        if (data != null ) {
            if(data.getImg_info() != null && data.getImg_info().size() > 0){
                for (int i = 0; i < data.getImg_info().size(); i++) {
                    fileList.add(TimeListUilts.subUrl(data.getImg_info().get(i))); //将文件名添加到集合，以后需要用来删除的
                    photoBeanList.add(new CheckedCarItemBean(data.getImg_info().get(i), false));
                    //如果以后显示多张，这里需要判断最后一个，然后设置true
                }
            }else{
                photoBeanList.add(new CheckedCarItemBean("", false));
            }
            if (data.getOption() != null) {
                qStatus = data.getOption().getQ();
                rStatus = data.getOption().getR();
                xStatus = data.getOption().getX();
                nStatus = data.getOption().getN();
                scratched = data.getOption().getA();
                painting = data.getOption().getP();
                sunken = data.getOption().getU();
                corrosion = data.getOption().getC();
            }
            if ("1".equals(xStatus)) {   //需更换
                changeView(replaceTv);
            }
            if ("1".equals(nStatus)) {    //缺少
                changeView(lackTv);
            }
            if ("1".equals(qStatus)) {
                scoreTwoCb.setChecked(true);
            }
            if ("1".equals(rStatus)) {
                scoreOneCb.setChecked(true);
            }
            setRadioButton(scratched, scratchedRg);
            setRadioButton(painting, paintingRg);
            setRadioButton(sunken, sunkenRg);
            setRadioButton(corrosion, corrosionRg);
        } else {
            photoBeanList.add(new CheckedCarItemBean("", false));
        }
        initViews();
    }

    private void setRadioButton(String status, RadioGroup rg) {
        if ("1".equals(status)) {
            ((RadioButton) rg.getChildAt(0)).setChecked(true);
        } else if ("2".equals(status)) {
            ((RadioButton) rg.getChildAt(1)).setChecked(true);
        } else if ("3".equals(status)) {
            ((RadioButton) rg.getChildAt(2)).setChecked(true);
        }
    }

    private void changeView(TextView v) {
        if (v == replaceTv) {
            replaceTv.setBackgroundResource(R.drawable.shape_text_frame_yellow);
            replaceTv.setTextColor(getResources().getColor(R.color.colorWhite));

            lackTv.setTextColor(getResources().getColor(R.color.colorFF030303));
            lackTv.setBackgroundResource(R.drawable.shape_text_frame_white);
        } else {
            replaceTv.setBackgroundResource(R.drawable.shape_text_frame_white);
            replaceTv.setTextColor(getResources().getColor(R.color.colorFF030303));

            lackTv.setTextColor(getResources().getColor(R.color.colorWhite));
            lackTv.setBackgroundResource(R.drawable.shape_text_frame_yellow);
        }
    }

    private void initViews() {
        photoPop = new SelectPhotoPop(this, popListener);
        photoRecycler.setLayoutManager(new GridLayoutManager(this, 3, LinearLayoutManager.VERTICAL, false));
        itemAdapter = new CheckedCarItemAdapter(this, R.layout.layout_item_car_surface_item_detail, photoBeanList);
        photoRecycler.setAdapter(itemAdapter);
        itemAdapter.setOnItemClickListener(this);
        scoreOneCb.setOnCheckedChangeListener(this);
        scoreTwoCb.setOnCheckedChangeListener(this);

        scratchedRg.setOnCheckedChangeListener(this);
        sunkenRg.setOnCheckedChangeListener(this);
        paintingRg.setOnCheckedChangeListener(this);
        corrosionRg.setOnCheckedChangeListener(this);
    }

    private View.OnClickListener popListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.rlty_select_camera:     //选择相机
                    GralleryFinalUtils.openCamera(gralleryCallBack);
                    break;
                case R.id.rlty_select_album:    //选择相册
                    RxGralleryFinalUtils.openRadioImage(InsuranceBarDetailActivity.this, rxGalleryCallBack);
                    break;
            }
            if (photoPop.isShowing()) {
                photoPop.dismiss();
            }
        }
    };

    private RxGralleryFinalUtils.RxGalleryFinalCallBack rxGalleryCallBack = new RxGralleryFinalUtils.RxGalleryFinalCallBack() {
        @Override
        public void onEvent(ImageRadioResultEvent imageRadioResultEvent) {
            Bitmap bitmap = BitmapUtil.getBitmapFromSDCard(imageRadioResultEvent.getResult().getOriginalPath());
            Bitmap sbitmap1 = BitmapUtil.storeImage(bitmap,900,1200);
            BitmapUtil.saveBitmapToLocal(sbitmap1,imageRadioResultEvent.getResult().getOriginalPath());
            refreshImage(imageRadioResultEvent.getResult().getOriginalPath(), currentIndex);
        }
    };

    private GalleryFinal.OnHanlderResultCallback gralleryCallBack = new GalleryFinal.OnHanlderResultCallback() {
        @Override
        public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
            if (reqeustCode == GralleryFinalUtils.CAMERA) {
                Bitmap bitmap = BitmapUtil.getBitmapFromSDCard(resultList.get(0).getPhotoPath());
                Bitmap sbitmap1 = BitmapUtil.storeImage(bitmap,900,1200);
                BitmapUtil.saveBitmapToLocal(sbitmap1,resultList.get(0).getPhotoPath());
                refreshImage(resultList.get(0).getPhotoPath(), currentIndex);
            }
        }

        @Override
        public void onHanlderFailure(int requestCode, String errorMsg) {

        }
    };

    protected void refreshImage(String url, int index) {
        photoBeanList.set(index, new CheckedCarItemBean(url, true));
        itemAdapter.notifyDataSetChanged();
    }

    @Override
    public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
        currentIndex = position;
        if (TextUtils.isEmpty(photoBeanList.get(position).getPhoto())) {
            //跳转相机
            photoPop.showAtLocation(this.findViewById(R.id.llty_root), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        } else {
            //跳转大图
            Intent bigIntent = new Intent(InsuranceBarDetailActivity.this, BigPhotoAndDescribeActivity.class);
            bigIntent.putExtra("classId", CarPhotoID.surfaceID);
            bigIntent.putExtra("sourceId", sourceID);
            bigIntent.putExtra("photoUrl", photoBeanList.get(position).getPhoto());
            if (fileList != null && fileList.size() > 0) {
                bigIntent.putExtra("fileName", TimeListUilts.subUrl(photoBeanList.get(position).getPhoto()));
            }
            bigIntent.putExtra("isSave", isSave);
            startIntent(bigIntent, 26);
        }
    }


    @Override
    protected void doOnNext(RxBusBean rxBusBean) {
        super.doOnNext(rxBusBean);
        if(rxBusBean.getRequestMark().equals(sourceID)){
            if (!TextUtils.isEmpty(photoBeanList.get(currentIndex).getPhoto())) {
                photoBeanList.set(currentIndex, new CheckedCarItemBean("", false));
            }
            itemAdapter = new CheckedCarItemAdapter(this, R.layout.layout_item_car_surface_item_detail, photoBeanList);
            itemAdapter.setOnItemClickListener(this);
            photoRecycler.setAdapter(itemAdapter);
        }
    }

    @Override
    public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
        return false;
    }


    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

        switch (compoundButton.getId()) {
            case R.id.cb_score_one:
                if (b) {
                    rStatus = "1";
                } else {
                    rStatus = "";
                }
                break;
            case R.id.cb_score_two:
                if (b) {
                    qStatus = "1";
                } else {
                    qStatus = "";
                }
                break;
        }
    }


    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int id) {
        switch (radioGroup.getId()) {
            case R.id.rg_scratched:
                scratchedFuncation(id);
                break;
            case R.id.rg_sunken:
                sunkenFuncation(id);
                break;
            case R.id.rg_painting:
                paintingFuncation(id);
                break;
            case R.id.rg_corrosion:
                corrosionFuncation(id);
                break;
        }
    }

    private void corrosionFuncation(int id) {
        switch (id) {
            case R.id.rbtn_corrosion_one:
                corrosion = "1";
                break;
            case R.id.rbtn_corrosion_two:
                corrosion = "2";
                break;
            case R.id.rbtn_corrosion_three:
                corrosion = "3";
                break;
        }
    }


    private void paintingFuncation(int id) {
        switch (id) {
            case R.id.rbtn_painting_one:
                painting = "1";
                break;
            case R.id.rbtn_painting_two:
                painting = "2";
                break;
            case R.id.rbtn_painting_three:
                painting = "3";
                break;
        }
    }

    private void sunkenFuncation(int id) {
        switch (id) {
            case R.id.rbtn_sunken_one:
                sunken = "1";
                break;
            case R.id.rbtn_sunken_two:
                sunken = "2";
                break;
            case R.id.rbtn_sunken_three:
                sunken = "3";
                break;
        }
    }

    private void scratchedFuncation(int id) {
        switch (id) {
            case R.id.rbtn_scratched_one:
                scratched = "1";
                break;
            case R.id.rbtn_scratched_two:
                scratched = "2";
                break;
            case R.id.rbtn_scratched_three:
                scratched = "3";
                break;
        }
    }


    @OnClick({R.id.iv_return, R.id.tv_save_info, R.id.tv_replace, R.id.tv_lack, R.id.tv_reset})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_return:
                onBackPressed();
                break;
            case R.id.tv_save_info:
                saveImg();
                break;
            case R.id.tv_replace:       //需要更换
                changeView(replaceTv);
                xStatus = "1";
                nStatus = "0";
                break;
            case R.id.tv_lack:          //缺少
                changeView(lackTv);
                nStatus = "1";
                xStatus = "0";
                break;
            case R.id.tv_reset:
                reset();
                break;
        }
    }

    private void reset() {
        resetRadioGroup(corrosionRg);
        resetRadioGroup(paintingRg);
        resetRadioGroup(sunkenRg);
        resetRadioGroup(scratchedRg);
        scoreOneCb.setChecked(false);
        scoreTwoCb.setChecked(false);
        lackTv.setTextColor(getResources().getColor(R.color.colorFF030303));
        lackTv.setBackgroundResource(R.drawable.shape_text_frame_white);
        replaceTv.setTextColor(getResources().getColor(R.color.colorFF030303));
        replaceTv.setBackgroundResource(R.drawable.shape_text_frame_white);
        qStatus = "";
        rStatus = "";
        nStatus = "-1";
        xStatus = "-1";
        scratched = "";
        painting = "";
        sunken = "";
        corrosion = "";
    }

    private void resetRadioGroup(RadioGroup group) {
        for (int i = 0; i < group.getChildCount(); i++) {
            ((RadioButton) group.getChildAt(i)).setChecked(false);
        }
    }

    private void saveImg() {
        SinglePhotoUpBean bean = new SinglePhotoUpBean();
        bean.setImg_info(getUpLoadImgList());
        bean.setAttr_id(sourceID);
        bean.setOption(getOption());
        bean.setId( CustomSharedPreferences.getString(this, KeyBean.CARID.valueOf(),KeyBean.FILE_NAME.valueOf()));
        HashMap<String, Object> build = new MapUtil()
                .put("data", new Gson().toJson(bean))
                .build();
        RxRequest.request(ShowType.SHOW, RxRequest.getClient(this, build).create(IApiActivityRequest.class).saveSurface()
                , new BaseSubscriber<TokenBean>(this) {
                    @Override
                    public void onSuccess(TokenBean o) {
                        Intent intent = new Intent();
                        intent.putExtra("sourceID", sourceID);
                        putColor(intent);
                        setResult(0, intent);
                        finish();
                    }

                    @Override
                    public void onFailure(Throwable e) {

                    }
                });
    }

    private void putColor(Intent intent) {
        if ("1".equals(nStatus) || "1".equals(xStatus) ||
                "3".equals(scratched) || "3".equals(painting) || "3".equals(sunken) || "3".equals(corrosion)) {
            intent.putExtra("color", "red");
        } else if ("2".equals(scratched) || "2".equals(painting) || "2".equals(sunken) || "2".equals(corrosion)) {
            intent.putExtra("color", "orange");
        } else if ("1".equals(scratched) || "1".equals(painting) || "1".equals(sunken) || "1".equals(corrosion) ||
                qStatus.equals("1") || rStatus.equals("1")) {
            intent.putExtra("color", "yellow");
        }
    }


    @Override
    public void onBackPressed() {
        Intent intent = new Intent();
        if (!isSave) {
            intent.putExtra("sourceID", sourceID);
            intent.putExtra("color", "green");
        }
        setResult(0, intent);
        finish();
    }

    /**
     * 设置选项
     *
     * @return
     */
    private SinglePhotoUpBean.Option getOption() {
        SinglePhotoUpBean.Option option = new SinglePhotoUpBean.Option();
        option.setQ(qStatus);
        option.setR(rStatus);
        option.setX(xStatus);
        option.setN(nStatus);
        option.setA(scratched);
        option.setP(painting);
        option.setU(sunken);
        option.setC(corrosion);
        return option;
    }

    /**
     * 将图片存到一个集合里面准备上传,并且提交到阿里云
     *
     * @return
     */
    private List<String> getUpLoadImgList() {
        List<String> photoList = new ArrayList<>();
        for (int i = 0; i < photoBeanList.size(); i++) {    //循环上传图片到阿里
            if (!TextUtils.isEmpty(photoBeanList.get(i).getPhoto())) {
                if (!photoBeanList.get(i).getPhoto().contains("http")) {
                    String fileName = TimeListUilts.getObjectKey() + ".png";
                    AliYunUtils.aLiYunUpLoadFuncation(
                            this,
                            sourceID,       //图片ID
                            fileName,                           //图片名
                            photoBeanList.get(i).getPhoto()     //图片路径
                            , null);

                    photoList.add(fileName);
                } else {
                    photoList.add(TimeListUilts.subUrl(photoBeanList.get(i).getPhoto()));
                }
            }
        }
        return photoList;
    }


}
